// 认证相关API服务
import axios from 'axios';
import { getToken, removeToken } from '../utils';

// 创建axios实例
const api = axios.create({
  baseURL: process.env.REACT_APP_API_URL || 'http://211.86.197.10:9091/api',
  timeout: 10000,
});

// 请求拦截器 - 添加token
api.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    // 处理401未授权错误
    if (error.response?.status === 401) {
      removeToken();
      window.location.href = '/login';
    }
    
    // 处理网络错误
    if (!error.response) {
      return Promise.resolve({
        success: false,
        message: '网络连接失败，请检查网络设置'
      });
    }
    
    return Promise.reject(error);
  }
);

class AuthService {
  // 管理员登录
  async adminLogin(credentials) {
    try {
      const response = await api.post('/auth/admin-login', credentials);
      return response;
    } catch (error) {
      console.error('管理员登录请求失败:', error);
      
      if (error.response?.data) {
        return error.response.data;
      }
      
      return {
        success: false,
        message: '网络连接失败，请检查网络设置'
      };
    }
  }

  // 登录
  async login(credentials) {
    try {
      const response = await api.post('/auth/login', credentials);
      return response;
    } catch (error) {
      console.error('登录请求失败:', error);
      
      if (error.response?.data) {
        return error.response.data;
      }
      
      return {
        success: false,
        message: '网络连接失败，请检查网络设置'
      };
    }
  }

  // 注册
  async register(userData) {
    try {
      const response = await api.post('/auth/register', userData);
      return response;
    } catch (error) {
      console.error('注册请求失败:', error);
      
      if (error.response?.data) {
        return error.response.data;
      }
      
      return {
        success: false,
        message: '网络连接失败，请检查网络设置'
      };
    }
  }

  // 获取用户信息
  async getUserInfo() {
    try {
      const response = await api.get('/auth/me');
      return response;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      
      if (error.response?.data) {
        return error.response.data;
      }
      
      return {
        success: false,
        message: '获取用户信息失败'
      };
    }
  }

  // 更新用户信息
  async updateProfile(userData) {
    try {
      const response = await api.put('/auth/profile', userData);
      return response;
    } catch (error) {
      console.error('更新用户信息失败:', error);
      return {
        success: false,
        message: '更新失败'
      };
    }
  }

  // 修改密码
  async changePassword(passwordData) {
    try {
      const response = await api.put('/auth/password', passwordData);
      return response;
    } catch (error) {
      console.error('修改密码失败:', error);
      return {
        success: false,
        message: '修改密码失败'
      };
    }
  }

  // 登出
  async logout() {
    try {
      await api.post('/auth/logout');
    } catch (error) {
      console.error('登出请求失败:', error);
    } finally {
      removeToken();
    }
  }

  // 刷新token
  async refreshToken() {
    try {
      const response = await api.post('/auth/refresh');
      return response;
    } catch (error) {
      console.error('刷新token失败:', error);
      removeToken();
      return {
        success: false,
        message: '登录已过期，请重新登录'
      };
    }
  }

  // 忘记密码
  async forgotPassword(email) {
    try {
      const response = await api.post('/auth/forgot-password', { email });
      return response;
    } catch (error) {
      console.error('发送重置密码邮件失败:', error);
      return {
        success: false,
        message: '发送失败，请稍后重试'
      };
    }
  }

  // 重置密码
  async resetPassword(token, newPassword) {
    try {
      const response = await api.post('/auth/reset-password', {
        token,
        password: newPassword
      });
      return response;
    } catch (error) {
      console.error('重置密码失败:', error);
      return {
        success: false,
        message: '重置失败，请重新申请'
      };
    }
  }

  // 验证邮箱
  async verifyEmail(token) {
    try {
      const response = await api.post('/auth/verify-email', { token });
      return response;
    } catch (error) {
      console.error('邮箱验证失败:', error);
      return {
        success: false,
        message: '验证失败'
      };
    }
  }

  // 发送验证邮件
  async sendVerificationEmail() {
    try {
      const response = await api.post('/auth/send-verification');
      return response;
    } catch (error) {
      console.error('发送验证邮件失败:', error);
      return {
        success: false,
        message: '发送失败'
      };
    }
  }
}

const authService = new AuthService();
export default authService;